<?php

namespace App\Console\Commands;

use App\Models\Template;
use App\Models\Article;
use Illuminate\Console\Command;
use App\Models\Brand;

class ReorganizeFormatTemplateByBrand extends Command {
    
    protected $signature = 'rftbb {batch}';
    protected $description = 'ReorganizeTemplate';
    
    public function __construct() {
        parent::__construct ();
    }
    
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function handle() {
        $this->error('开始整理加盟模板数据，使用品牌匹配模板。');
        $batch = $this->argument('batch');
        $brands = Brand::select('industry_id', 'oldprice', 'name')->get();
        $i = 0;
        foreach ($brands as $brand) {
            $articles = Article::where('title', 'like', '%'.$brand->name.'%')->select('title', 'content')->get();
            if(count($articles) > 0) {
                $this->saveTemplate($articles, $brand, $batch);
                $i += count($articles);
                $this->info('当前已处理：'.$i.' 条');
            }
            unset($articles);
        }
        
        $this->error('整理完成，共处理：'.$i.' 条');
    }
    
    public function saveTemplate($articles, $b, $batch) {
        $i = 1;
        $count = count($articles);
        foreach ($articles as $article) {
            Template::create([
                'industry_id' => $b->industry_id,
                'name' => $this->formatContent($article->title, $b),
                'batch' => $batch,
                'content' => $this->formatContent($article->content, $b),
            ]);
            $this->info('品牌：'.$b->name.':'.'模板：'.$i.'/'.$count.'  '.$article->title);
            $i++;
            unset($article);
        }
    }
    
    public function formatContent($content, $brand) {
        $format = str_replace($brand->name, "{name}", $content);
        $format = str_replace($brand->oldprice, "{price}", $format);
        return $format;
    }
}
